package com.example.springbootServiceNetwork.demos.web.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springbootServiceNetwork.demos.web.Config.JwtInfo;
import com.example.springbootServiceNetwork.demos.web.Config.Result;
import com.example.springbootServiceNetwork.demos.web.Config.ResultEnum;
import com.example.springbootServiceNetwork.demos.web.Dao.DictDao;
import com.example.springbootServiceNetwork.demos.web.Dao.DictItemDao;
import com.example.springbootServiceNetwork.demos.web.Entity.Dict;
import com.example.springbootServiceNetwork.demos.web.Entity.DictItem;
import com.example.springbootServiceNetwork.demos.web.Service.DictService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;
import java.util.*;

import static com.example.springbootServiceNetwork.demos.web.Tool.PinyinUtil.getFirstLetter;
import static com.example.springbootServiceNetwork.demos.web.Tool.WrapperMethodUtil.bollPurvieTool;

@Service
public class DictServiceImpl implements DictService {

    @Resource
    private DictDao dictDao;

    @Resource
    private DictItemDao dictItemDao;

    @Resource //它定义了事务管理器的基本功能，如开始、提交、回滚事务等。
    PlatformTransactionManager platformTransactionManager;
    @Resource //它定义了事务的属性，如事务的传播行为、隔离级别、超时时间等。
    TransactionDefinition transactionDefinition;



    /**
     * 查询字典（父类+子类）
     */
    @Override
    public Result queryDictGet(String child,JwtInfo jwtInfo){
        Result result =new Result();
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                result.setMsg(ResultEnum.SUCCESS.getData());
                result.setCode(ResultEnum.SUCCESS.getCode());
                List<Dict> list = dictDao.selectList(null);
                List<DictItem> list2=new ArrayList<>();
                HashMap<String,Object> map =new HashMap<>();
                if (Objects.equals(child, "true")){
                    list2 = dictItemDao.selectList(null);
                    map.put("dictItemList",list2);
                }
                map.put("dictList",list);
                result.setData(map);
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return  result;
    }

    /**
     * 新增字典(父类)
     */
    @Override
    public Result addDict(Dict dict, JwtInfo jwtInfo){
        TransactionStatus transactionStatus=platformTransactionManager.getTransaction(transactionDefinition);
        Result result = new Result();
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                dict.setCreatTime(new Date());
                if (dict.getPermissions()==null){
                    dict.setPermissions("ordinary");
                }
                if (dict.getName()==null){
                    result.setCode(ResultEnum.BADREQUEST.getCode());
                    result.setMsg(ResultEnum.BADREQUEST.getData());
                }else {
                    int res =dictDao.insert(dict);
                    if (res==1){
                        platformTransactionManager.commit(transactionStatus);
                        result.setCode(ResultEnum.SUCCESS.getCode());
                        result.setMsg(ResultEnum.SUCCESS.getData());
                    }else {
                        platformTransactionManager.rollback(transactionStatus);
                        result.setCode(ResultEnum.BADREQUEST.getCode());
                        result.setMsg(ResultEnum.BADREQUEST.getData());
                    }
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }

    /**
     * 修改字典(父类)
     */
    @Override
    public Result updateDict(Dict dict, JwtInfo jwtInfo){
        Result result = new Result();
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                int res=dictDao.updateById(dict);
                if (res==1){
                    result.setCode(ResultEnum.SUCCESS.getCode());
                    result.setMsg(ResultEnum.SUCCESS.getData());
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }

        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }
    /**
     * 删除(父类)
     */
    @Override
    public Result deleteDict(Dict dict, JwtInfo jwtInfo){
        Result result = new Result();
        TransactionStatus transactionStatus=platformTransactionManager.getTransaction(transactionDefinition);
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                int res=dictDao.deleteById(dict);
                if (res==1){
                    LambdaQueryWrapper<DictItem> lqw = new LambdaQueryWrapper<>();
                    lqw.eq(DictItem::getParentId,dict.getId());
                    List<DictItem> dictItemList = dictItemDao.selectList(lqw);
                    int delNum = 0;
                    for (DictItem item :dictItemList){
                        int res2 = dictItemDao.deleteById(item);
                        delNum = delNum +res2;
                    }
                    if (dictItemList.size()==delNum){
                        result.setCode(ResultEnum.SUCCESS.getCode());
                        result.setMsg(ResultEnum.SUCCESS.getData());
                        platformTransactionManager.commit(transactionStatus);
                    }else {
                        platformTransactionManager.rollback(transactionStatus);
                        result.setCode(ResultEnum.BADREQUEST.getCode());
                        result.setMsg("删除失败！");
                    }
                }else {
                    platformTransactionManager.rollback(transactionStatus);
                    result.setCode(ResultEnum.BADREQUEST.getCode());
                    result.setMsg("删除失败！");
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }



    /**
     * 查询字典接口 (子类)
     */
    @Override
    public Result queryDict(Dict dict, JwtInfo jwtInfo){
        Result result =new Result();
        try {
            LambdaQueryWrapper<Dict> lqwDict =new LambdaQueryWrapper<>();
            lqwDict.eq(Dict::getId,dict.getId());
            lqwDict.eq(Dict::getStatus,1);
            Dict dict1 =dictDao.selectOne(lqwDict);
            List<DictItem> list =new ArrayList<>();
            if (dict1.getPermissions().equals("ordinary")){
                LambdaQueryWrapper<DictItem> lqw =new LambdaQueryWrapper<>();
                lqw.eq(DictItem::getParentId,dict1.getId());
                lqw.eq(DictItem::getStatus,1);
                list =dictItemDao.selectList(lqw);
            }else {
                for (String item2:jwtInfo.getPurview()){
                    if (item2.contains(dict1.getPermissions())){
                        LambdaQueryWrapper<DictItem> lqw =new LambdaQueryWrapper<>();
                        lqw.eq(DictItem::getParentId,dict1.getId());
                        lqw.eq(DictItem::getStatus,1);
                        list =dictItemDao.selectList(lqw);
                        break;
                    }
                }
            }
            if (list.isEmpty()){
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg(dict1.getName()+"查询成功");
                result.setData(list);
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg(dict1.getName()+"查询成功");
                result.setData(list);
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return  result;
    }


    /**
     * 新增字典(子类)
     */
    @Override
    public Result addDictItem(DictItem dictItem, JwtInfo jwtInfo){
        Result result = new Result();
        try {
            LambdaQueryWrapper<DictItem> lqw =new LambdaQueryWrapper<>();
            lqw.eq(DictItem::getParentId,dictItem.getParentId());
            List<DictItem> list = dictItemDao.selectList(lqw);
            String numId="1";
            if (!list.isEmpty()){
                numId = String.valueOf(Integer.parseInt(list.get(list.size()-1).getDictId())+1);
            }
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                //更新时间
                dictItem.setCreatTime(new Date());
                //更新字典序号id
                dictItem.setDictId(numId);
                //更新字典编码
                if (dictItem.getDictCode()==null|| dictItem.getDictCode().equals("")){
                    dictItem.setDictCode(getFirstLetter(dictItem.getDictName()+"-"+numId));
                }
                if (dictItem.getDictName()==null){
                    result.setCode(ResultEnum.BADREQUEST.getCode());
                    result.setMsg(ResultEnum.BADREQUEST.getData());
                }else {
                    int res =dictItemDao.insert(dictItem);
                    if (res==1){
                        result.setCode(ResultEnum.SUCCESS.getCode());
                        result.setMsg(ResultEnum.SUCCESS.getData());
                    }else {
                        result.setCode(ResultEnum.BADREQUEST.getCode());
                        result.setMsg(ResultEnum.BADREQUEST.getData());
                    }
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }

    /**
     * 修改字典(子类)
     */
    @Override
    public Result updateDictItem(DictItem dictItem, JwtInfo jwtInfo){
        Result result = new Result();
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
//                dictItem.setDictCode(getFirstLetter(dictItem.getDictName()+"-"+dictItem.getDictId()));
                int res=dictItemDao.updateById(dictItem);
                if (res==1){
                    result.setCode(ResultEnum.SUCCESS.getCode());
                    result.setMsg(ResultEnum.SUCCESS.getData());
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }

        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }
    /**
     * 删除字典(子类)
     */
    @Override
    public Result deleteDictItem(DictItem dictItem, JwtInfo jwtInfo){
        Result result = new Result();
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                int res=dictItemDao.deleteById(dictItem);
                if (res==1){
                    result.setCode(ResultEnum.SUCCESS.getCode());
                    result.setMsg(ResultEnum.SUCCESS.getData());
                }else {
                    result.setCode(ResultEnum.BADREQUEST.getCode());
                    result.setMsg("删除失败！");
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }

    /**
     * 自动生成字典编码值（子类）
     */
    @Override
    public Result autoDictCode(DictItem dictItem,JwtInfo jwtInfo){
        Result  result = new Result();
        Number count = dictItemDao.selectCount(null);
        String code = getFirstLetter(dictItem.getDictName()+"-"+count);
        if (code.length()>=2&&!code.contains("null")){
            result.setMsg("编码生成成功！");
            result.setCode(200);
            result.setData(code);
        }else {
            result.setMsg("编码生成失败请手动编写！");
            result.setCode(500);
        }
      return result;
    }

}
